//
//  RBCartVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/5/26.
//

#import "RBCartVC.h"
#import "RBDefine.h"
#import "UIView+RBAdd.h"
#import "UIScrollView+RBAdd.h"
#import <Masonry.h>
#import "RBThemeConfig.h"
#import <UIColor+YYAdd.h>
#import <UIView+YYAdd.h>
#import "RBPager.h"
#import "RanTool.h"
#import "RBGradientView.h"
#import <UIImage+YYAdd.h>
#import "RBCartListCell.h"
#import "RBCollectionReusableView.h"
#import "RBSystemDetailGuessCell.h"
#import "RBConfirmOrderVC.h"
#import "UIViewController+RBAdd.h"
#import "RBCartResponse.h"
#import "RBGoodsDetailVC.h"

@interface RBCartVC ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property(nonatomic, assign)BOOL editState;
@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)UIView *bottomView;
@property(nonatomic, strong)UILabel *selectAllL;
@property(nonatomic, assign)BOOL selectAll;
@property(nonatomic, strong)UILabel *priceL;
@property(nonatomic, strong)UILabel *actionL;

@property(nonatomic, strong) RBCartResponse *response;

@end

@implementation RBCartVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getData];
}

#pragma mark - Private

- (void)setup
{
    self.title = nil;
    self.navigationItem.leftBarButtonItem = ({
        UIBarButtonItem *item = [UIBarButtonItem.alloc initWithTitle:@"购物车" style:UIBarButtonItemStylePlain target:nil action:nil];
        [item setTitleTextAttributes:@{NSForegroundColorAttributeName: [RBThemeConfig textBlackColor], NSFontAttributeName: [UIFont systemFontOfSize:Zoom(18)]} forState:UIControlStateNormal];
        item;
    });
    self.navigationItem.rightBarButtonItem = [self rightBarButtonItem];
    self.view.backgroundColor = [RBThemeConfig bgGrayColor];
    self.collectionView.hidden = NO;
    self.bottomView.hidden = NO;
}

- (void)reloadBottomBar
{
    self.selectAllL.attributedText = [self selectAllAttWithSel:self.selectAll];
    if (self.editState)
    {
        self.priceL.attributedText = nil;
        self.actionL.text = @"删除";
    }
    else
    {
        NSInteger count = 0;
        NSString *price = @"0";
        NSArray *models = [RanTool modelsWithSection:0 dataSource:self.dataSource];
        for (RBCartModel *model in models)
        {
            if (model.selected)
            {
                count ++;
                price = [RanTool num:price plusNum:model.good_price];
            }
        }
        self.priceL.attributedText = [self priceAttWithPrice:price];
        self.priceL.textAlignment = NSTextAlignmentCenter;
        self.actionL.text = [NSString stringWithFormat:@"结算(%zd)", count];
    }
}

- (void)fillData
{
    __weak typeof(self) weakSelf = self;
    [self.dataSource removeAllObjects];
    [self.dataSource addObject:({
        RBGroupModel *group = RBGroupModel.new;
        group.sectionInset = UIEdgeInsetsMake(Zoom(10), 0, Zoom(10), 0);
        group.minimumLineSpacing = Zoom(10);
        group.cellModels = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            for (RBCartModel *model in self.response.data)
            {
                [arrayM addObject:({
                    RBCellModel *cellModel = RBCellModel.new;
                    cellModel.eventBlock1 = ^(NSInteger type, NSInteger index, RBCartModel *listModel) {
                        [weakSelf cellEventWithType:type index:index listModel:listModel];
                    };
                    cellModel.reuseCellIdentifier = NSStringFromClass(RBCartListCell.class);
                    cellModel.cellData = model;
                    cellModel;
                })];
            }
            arrayM;
        });
        group;
    })];
    [self.dataSource addObject:({
        RBGroupModel *group = RBGroupModel.new;
        group.headerReuseIdentifier = NSStringFromClass(RBCollectionReusableView.class);
        group.headerReferenceSize = CGSizeMake(kRBMainScreenWidth, Zoom(60));
        group.headerView = ({
            UIView *view = [RanTool labelWithFontSize:Zoom(18) weight:2 color:[RBThemeConfig textBlackColor] align:1 text:@"猜您喜欢"];
            view;
        });
        group.sectionInset = UIEdgeInsetsMake(0, Zoom(15), Zoom(75), Zoom(15));
        group.minimumLineSpacing = Zoom(11);
        group.cellModels = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            for (NSInteger i = 0; i < self.response.likes.count; i++)
            {
                [arrayM addObject:({
                    RBCellModel *cellModel = RBCellModel.new;
                    cellModel.cellData = self.response.likes[i];
                    cellModel.reuseCellIdentifier = NSStringFromClass(RBSystemDetailGuessCell.class);
                    cellModel.cellSelectBlock = ^(NSIndexPath *indexPath) {
                        RBCartLikeModel *model = [RanTool modelWithSection:indexPath.section row:indexPath.row dataSource:weakSelf.dataSource];
                        RBGoodsDetailVC *vc = RBGoodsDetailVC.new;
                        vc.id = model.id;
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    };
                    cellModel;
                })];
            }
            arrayM;
        });
        group;
    })];
    [self.collectionView reloadData];
    [self reloadBottomBar];
}

#pragma mark - Network

- (void)getData
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        
    } path:@"api/member_cart" post:YES log:YES responseClass:RBCartResponse.class desView:self.view showHud:!self.response showPlaceHolder:NO sucBlock:^(id data) {
        weak_self.response = data;
        [weak_self fillData];
    } failBlock:^(RBCartResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

#pragma mark - Event

- (void)rightBarButtonItemTapped
{
    self.editState = !self.editState;
    self.navigationItem.rightBarButtonItem = [self rightBarButtonItem];
    [self reloadBottomBar];
}

- (void)cellEventWithType: (NSInteger)type index: (NSInteger)index listModel: (RBCartModel *)listModel
{
    if(type == RBCartListCellActionShopSelectEvent)
    {
//        listModel.selected = !listModel.selected;
//        for (RBCartListGoodsModel *model in listModel.items)
//        {
//            model.selected = listModel.selected;
//        }
    }
    else if(type == RBCartListCellActionGoodsSelectEvent)
    {
//        BOOL shopSelect = YES;
//
//        RBCartListGoodsModel *goodsModel = listModel.items[index];
//        goodsModel.selected = !goodsModel.selected;
//        for (RBCartListGoodsModel *model in listModel.items)
//        {
//            if (!model.selected)
//            {
//                shopSelect = NO;
//                break;
//            }
//        }
//        listModel.selected = shopSelect;
        listModel.selected = !listModel.selected;
    }
    else if (type == RBCartListCellActionCountChangedEvent)
    {
        
    }
    else if(type == RBCartListCellActionCountPlusEvent)
    {
//        RBCartListGoodsModel *model = listModel.items[index];
//        model.count++;
    }
    else if(type == RBCartListCellActionCountMinusEvent)
    {
//        RBCartListGoodsModel *model = listModel.items[index];
//        if (model.count > 1)
//        {
//            model.count++;
//        }
    }
    
    if (type == RBCartListCellActionShopSelectEvent || type == RBCartListCellActionGoodsSelectEvent)
    {
        BOOL selectAll = YES;
        NSArray *models = [RanTool modelsWithSection:0 dataSource:self.dataSource];
        for (RBCartModel *model in models)
        {
            if(!model.selected)
            {
                selectAll = NO;
                break;;
            }
        }
        self.selectAll = selectAll;
    }
    [self.collectionView reloadData];
    [self reloadBottomBar];
}

- (void)selectAllBtnTapped
{
    self.selectAll = !self.selectAll;
    NSArray *models = [RanTool modelsWithSection:0 dataSource:self.dataSource];
    for (RBCartModel *listModel in models)
    {
        listModel.selected = self.selectAll;
//        for (RBCartListGoodsModel *model in listModel.items)
//        {
//            model.selected = self.selectAll;
//        }
    }
    [self.collectionView reloadData];
    [self reloadBottomBar];
}

- (void)actionBtnTapped
{
    __weak typeof(self) weak_self = self;
    NSMutableArray *models = NSMutableArray.array;
    NSMutableArray *ids = NSMutableArray.array;
    for (RBCartModel *model in self.response.data)
    {
        if(model.selected)
        {
            [models addObject:model];
            [ids addObject:model.id];
        }
    }
    if(self.editState)
    {
        if(models.count < 1)
        {
            [self.view showTip:@"请选择要删除的商品" completion:nil];
            return;
        }
        [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
            dicM[@"ids"] = [ids componentsJoinedByString:@","];
        } path:@"api/cart_del" post:YES log:YES responseClass:RBResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(id data) {
            weak_self.response = nil;
            [weak_self.dataSource removeAllObjects];
            [weak_self fillData];
            [weak_self getData];
        } failBlock:^(RBResponse *data) {
            [weak_self.view showTip:data.message completion:nil];
        } reloadBlock:nil];
    }
    else
    {
        if(models.count > 1)
        {
            [self.view showTip:@"只能选择一件商品结算" completion:nil];
            return;
        }
        if(models.count < 1)
        {
            [self.view showTip:@"请选择要购买的商品" completion:nil];
            return;
        }
        RBConfirmOrderVC *vc = RBConfirmOrderVC.new;
        vc.type = RBConfirmOrderTypeFromCart;
        vc.cartId = ids.firstObject;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - UICollectionViewDataSource & UICollectionViewDelegate

kRBCollectionViewDataSourceAndDelegateAuto(self.dataSource);

#pragma mark - Setter

#pragma mark - Getter

- (UIBarButtonItem *)rightBarButtonItem
{
    UIBarButtonItem *item = [UIBarButtonItem.alloc initWithTitle:self.editState? @"完成": @"管理" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemTapped)];
    [item setTitleTextAttributes:@{NSForegroundColorAttributeName: [RBThemeConfig textGrayColor], NSFontAttributeName: [UIFont systemFontOfSize:Zoom(13)]} forState:UIControlStateNormal];
    return item;
}

- (NSAttributedString *)selectAllAttWithSel: (BOOL)sel
{
    UIFont *font = [UIFont systemFontOfSize:Zoom(13)];
    return [RanTool attributeStringMaker:^(NSMutableArray *maker) {
        [maker addAttributeStringWithImage:sel? [UIImage imageNamed:@"addressListDefault"]: [UIImage imageNamed:@"unsel"] imageSize:CGSizeMake(Zoom(16), Zoom(16)) maxFont:font];
        [maker addAttributeStringWithFont:font color:[UIColor colorWithHexString:@"#BFBFBF"] string:@" 全选"];
    }];
}

- (NSAttributedString *)priceAttWithPrice: (NSString *)price
{
    return [RanTool attributeStringMaker:^(NSMutableArray *maker) {
        [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(13)] color:[UIColor colorWithHexString:@"#BFBFBF"] string:@"合计"];
        [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(16)] color:UIColor.whiteColor string:@" ¥"];
        NSArray *priceArray = [price componentsSeparatedByString:@"."];
        if (priceArray.count)
        {
            [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(21)] color:UIColor.whiteColor string:priceArray[0]];
        }
        if (priceArray.count == 2)
        {
            [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(14)] color:UIColor.whiteColor string:@"."];
            [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(14)] color:UIColor.whiteColor string:priceArray[1]];
        }
        else
        {
            [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(14)] color:UIColor.whiteColor string:@".00"];
        }
    }];
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        self.collectionView = ({
            UICollectionViewFlowLayout *layout = UICollectionViewFlowLayout.new;
            layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize;
            UICollectionView *view = [UICollectionView.alloc initWithFrame:CGRectZero collectionViewLayout:layout];
            view.showsVerticalScrollIndicator = NO;
            view.showsHorizontalScrollIndicator = NO;
            view.dataSource = self;
            view.delegate = self;
            view.backgroundColor = UIColor.clearColor;
            kRBIgnoreScrollViewInsetsAdjust(view);
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(0);
                make.right.mas_equalTo(0);
                make.bottom.mas_equalTo(0);
                make.top.mas_equalTo(0);
            }];
            view;
        });
    }
    return _collectionView;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource)
    {
        self.dataSource = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            arrayM;
        });
    }
    return _dataSource;
}

- (UIView *)bottomView
{
    if (!_bottomView)
    {
        self.bottomView = ({
            UIView *view = UIView.new;
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.centerX.mas_equalTo(0);
                make.width.mas_equalTo(Zoom(350));
                make.height.mas_equalTo(Zoom(60));
            }];
            view.backgroundColor = [UIColor colorWithHexString:@"#595959"];
            [view rbSetCornerRadius:Zoom(30)];
            
            self.selectAllL = UILabel.new;
            [self.selectAllL addPriority:2];
            [self.selectAllL rbAddTapGesWithTarget:self action:@selector(selectAllBtnTapped)];
            [view h_view_addView:self.selectAllL withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:Zoom(16) right:0 centerY:0];
            
            self.priceL = UILabel.new;
            [view h_view_addView:self.priceL withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerY:0];
            
            RBGradientView *actionView = [RBGradientView gradientViewWithColors:@[[UIColor colorWithHexString:@"#518CFF"], [UIColor colorWithHexString:@"#2A6DF0"]] locations:nil vertical:NO];
            [actionView rbAddTapGesWithTarget:self action:@selector(actionBtnTapped)];
            [actionView rbSetCornerRadius:Zoom(20)];
            [actionView view_addView:({
                UILabel *view = [RanTool labelWithFontSize:Zoom(15) weight:1 color:UIColor.whiteColor align:1 text:@""];
                self.actionL = view;
                view;
            }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
            [view h_view_addView:actionView withHeight:Zoom(40) width:Zoom(106) top:CGFLOAT_MIN bottom:CGFLOAT_MIN left:0 right:Zoom(12) centerY:YES];
            
            view;
        });
    }
    return _bottomView;
}

@end
